package org.skatiger.jrove.component.html;

import java.io.IOException;

import javax.el.ELException;

import org.skatiger.jrove.JroveContext;
import org.skatiger.jrove.JroveException;
import org.skatiger.jrove.MetaRuleset;
import org.skatiger.jrove.component.UIComponent;
import org.skatiger.jrove.component.UIResource;
import org.skatiger.jrove.component.UIViewRoot;
import org.skatiger.jrove.resource.Resource;
import org.skatiger.jrove.tag.ComponentConfig;
import org.skatiger.jrove.tag.ComponentRule;
import org.skatiger.jrove.tag.MetaTagHandler;
import org.skatiger.jrove.tag.TagAttribute;
import org.skatiger.jrove.util.ComponentSupport;
import org.skatiger.jrove.util.StringUtils;

public class HtmlResourceHandler extends MetaTagHandler {
	private final String componentClass;
	private final TagAttribute id;
	private final TagAttribute target;

	public HtmlResourceHandler(ComponentConfig config) {
		super(config);
		this.componentClass = config.getComponentClass();
		this.id = this.getAttribute("id");
		this.target = this.getAttribute("target");
	}

	public void apply(JroveContext ctx, UIComponent parent) throws IOException,
			JroveException, ELException {
		UIComponent c = ctx.getViewContext().createComponent(componentClass);
		UIViewRoot root = ComponentSupport.getViewRoot(ctx, parent);
		this.setAttributes(ctx, c);
		String uid = null;
		if (this.id != null) {// get id from tag attribute id
			uid = this.id.getValue(ctx).trim();
		}
		if (StringUtils.isBlank(uid)) { // get id from viewRoot createUniqueId
										// method
			if (root != null) {
				uid = root.createUniqueId(ctx.getViewContext(), null);
			}
		}
		c.setId(uid);
		c.setTransient(true);
		// mark it owned by a facelet instance
		c.getAttributes().put(ComponentSupport.MARK_CREATED, uid);

		String _target = null;
		if (target != null) {
			String targetValue = target.getValue(ctx);
			if (StringUtils.isNotBlank(targetValue)) {
				_target = targetValue;
			}
		}
		if (UIResource.TARGET_HEAD.equals(_target)) {
			root.addResource((Resource) c);
		} else {
			parent.getChildren().add(c);
		}
	}

	@Override
	protected MetaRuleset createMetaRuleset(Class<?> type) {
		MetaRuleset m = super.createMetaRuleset(type);
		// ignore standard component attributes
		m.ignore("id");
		m.addRule(ComponentRule.INSTANCE);
		return m;
	}
}
